package com.atguigu2;
/**
 * @auther user
 * @date 2021/12/6 - 2:40
 */

import com.utils.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @Description 演示PreparedStatement替换Statement.解决SQL注入问题
 * @createTime 2021/12/6 2:40
 * @author user
 */
public class PreparedStatementTest {
    @Test
    public void testLogin(){
        //输入用户名和密码
        String user = null;
        String password = null;
        //Sql注入
        String sql = "SELECT user,password FROM user_table WHERE user = ? AND password = ? ";
        User queryUser = getInstance(User.class,sql,user,password);
        if (queryUser != null){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败，用户名或密码错误");
        }
    }
    
    /**
     * @Description 针对于不同的表的通用查询操作，返回表中的一条记录
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T getInstance(Class<T> clazz,String sql,Object ...args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //1 获取连接
            connection = JDBCUtils.getConnection();
            //2 预编译sql,返回PreparedStatement实例
            preparedStatement = connection.prepareStatement(sql);
            //3 填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            //4 执行，返回ResultSet结果集
            resultSet = preparedStatement.executeQuery();
            //5 处理结果集
            //获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //获取结果集中的总列数
            int columnCount = metaData.getColumnCount();
            if (resultSet.next()){
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取列别名
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    //获取列值
                    Object columnValue = resultSet.getObject(i + 1);
                    //通过反射，给t对象的columnLabel属性赋值columnValue
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t,columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //6 关闭资源
            JDBCUtils.closeResource(connection,preparedStatement,resultSet);
        }
        return null;
    }

}
